前期準備工作已經完成,接下來就把金流串接上我們的購物網站上去~
前端表單
Shoping/Index.cshtml
<form action="/Shoping/Checkout" method="post">
<div class="row mb-3">
<label for="colFormLabel" class="col-sm-2 col-form-label">寄送地址:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="adress" name="adress" placeholder="請輸入地址">
</div>
</div>
<div class="row mb-3">
<label for="colFormLabel" class="col-sm-2 col-form-label">聯絡電話:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="phone" name="phone" placeholder="請輸入聯絡電話">
</div>
</div>
<div class="row mb-3">
<label for="colFormLabel" class="col-sm-2 col-form-label">寄送姓名:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" placeholder="請輸入姓名">
</div>
</div>
<input type="number" id="all_number" name="all_number" class="d-none" value=@ViewBag.all_number>
<p>總價:@ViewBag.all_number</p>
<div class="d-grid gap-2 col-6 mx-auto">
<button class="btn btn-outline-primary" type="submit">結帳</button>
</div>
</form>
控制器執行串接
ShopingController.cs
[HttpPost]
public async Task<IActionResult> Checkout()
{
// 獲取當前時間
DateTime currentTime = DateTime.Now;
// 將時間轉換為數字格式(例如 Unix 時間戳)
long numericTime = ((DateTimeOffset)currentTime).ToUnixTimeSeconds();
//內部產生訂單
var order = new Order
{
order_number ="0000"+ Request.Cookies["UserVerify"] + Request.Form["all_number"]+ numericTime,
adress = Request.Form["adress"],
phone = Request.Form["phone"],
price = int.Parse(Request.Form["all_number"]),
user_id = int.Parse(Request.Cookies["UserVerify"]),
manufacturer_id = 0,
payment = false
};
_db.Order.Add(order);
_db.SaveChanges();
//訂單下的詳細物件
var shop = _db.Shop.Where(u => u.user_id == int.Parse(Request.Cookies["UserVerify"])).ToList();
foreach (var item in shop)
{
var product = _db.Product.Find(item.product_id);
int product_number = product.price * item.number;
var items = new Item
{
order_id = order.order_number,
product_id = item.product_id,
product_name = product.name,
price = product_number,
user_id = int.Parse(Request.Cookies["UserVerify"]),
manufacturer_id = product.manufacturer_id
};
_db.Item.Add(items);
_db.SaveChanges();
}
//訂單記錄完成之後刪除購物車
var Shoping = _db.Shop.Where(u => u.user_id == int.Parse(Request.Cookies["UserVerify"])).ToList();
_db.Shop.RemoveRange(Shoping); // 或者使用 _db.RemoveRange(Shoping);
_db.SaveChanges();
//連接綠界金流
var appSettings = Configuration.GetSection("ECPay");
string ItemName = "shopping";
DateTime now = DateTime.Now;
string formattedDateTime = now.ToString("yyyy/MM/dd HH:mm:ss");
string MerchantTradeNo = order.order_number;
string TradeDesc = "shopping";
int TotalAmount = order.price;
string input = "HashKey="+ appSettings["HashKey"] + "&ChoosePayment=Credit&EncryptType=1&ItemName=" + ItemName +"&MerchantID="+ appSettings["MerchantID"] + "&MerchantTradeDate="+ formattedDateTime + "&MerchantTradeNo="+ MerchantTradeNo + "&PaymentType=aio&ReturnURL="+ appSettings["ReturnURL"]+ "&TotalAmount="+ TotalAmount+ "&TradeDesc=" + TradeDesc + "&HashIV=" + appSettings["HashIV"];
//Console.WriteLine(input);
input = Encryption.CheckMacValue(input);
// 创建要发送的 JSON 对象
var jsonData = new
{
CheckMacValue = input,
ChoosePayment = "Credit",
EncryptType = 1,
MerchantID = appSettings["MerchantID"],
MerchantTradeDate = formattedDateTime,
MerchantTradeNo = MerchantTradeNo,
PaymentType = "aio",
TotalAmount = TotalAmount,
TradeDesc = TradeDesc,
ItemName = ItemName,
ReturnURL = appSettings["ReturnURL"]
};
// 将 JSON 对象转换为 application/x-www-form-urlencoded 格式的字符串
var formData = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "CheckMacValue", input },
{ "ChoosePayment", jsonData.ChoosePayment },
{ "EncryptType", jsonData.EncryptType.ToString() },
{ "MerchantID", jsonData.MerchantID },
{ "MerchantTradeDate", jsonData.MerchantTradeDate },
{ "MerchantTradeNo", jsonData.MerchantTradeNo },
{ "PaymentType", jsonData.PaymentType },
{ "TotalAmount", jsonData.TotalAmount.ToString() },
{ "TradeDesc", jsonData.TradeDesc },
{ "ItemName", jsonData.ItemName },
{ "ReturnURL", jsonData.ReturnURL }
});
// 发送 POST 请求
var response = await _httpClient.PostAsync(appSettings["PostUrl"], formData);
//return Content(await formData.ReadAsStringAsync(), "application/x-www-form-urlencoded");
// 处理响应
if (response.IsSuccessStatusCode)
{
// 处理成功的情况
var htmlContent = await response.Content.ReadAsStringAsync();
return View("Checkout", htmlContent);
//return Content(htmlContent, "text/html");
}
else
{
// 处理失败的情况
return RedirectToAction("Index", "Home");
}
}
這裡在把資料送給綠界金流之前,會先在網站的資料庫為這筆訂單建檔,之後才會發給綠界金流
成功之後綠界會發一個網頁讓使用者填自己的信用卡資料結帳
這樣子串接就完成啦~